#include "StdAfx.h"
#include "../Engine/Tile.hpp"

namespace he
{
	Tile::Tile(unsigned short X, unsigned short Y)
		: m_X(X), m_Y(Y)
	{
		m_Normals[0] = m_Normals[1] = Ogre::Vector3(0, 1, 0);
	}

	void Tile::set_deep(unsigned short Vertex, float Height, bool RecalculateNormals, bool Absolute)
	{
		if(Absolute)
			get_vertex(Vertex)->y = Height / 127;
		else
			get_vertex(Vertex)->y += Height / 127;
		if(RecalculateNormals)
			recalculate_normals();
	}

	Ogre::Vector3 *Tile::get_vertex(unsigned short Number) const
	{
		return m_Vertices[Number];
	}

	void Tile::set_normals(Ogre::Vector3 const &Normal0, Ogre::Vector3 const &Normal1)
	{
		m_Normals[0] = Normal0;
		m_Normals[1] = Normal1;
	}

	Ogre::Vector3 const &Tile::get_normal(unsigned short Index) const
	{
		return m_Normals[Index];
	}

	void Tile::set_vertices(Ogre::Vector3 *pV0, Ogre::Vector3 *pV1, Ogre::Vector3 *pV2, Ogre::Vector3 *pV3)
	{
		m_Vertices[0] = pV0;
		m_Vertices[1] = pV1;
		m_Vertices[2] = pV2;
		m_Vertices[3] = pV3;
	}

	void Tile::recalculate_normals()
	{
		Ogre::Vector3 *p_n0 = get_vertex(0), *p_n1 = get_vertex(1), *p_n2 = get_vertex(2),
			*p_n3 = get_vertex(3);
		// Set the normal
		set_normals(Ogre::Math::calculateBasicFaceNormal(*p_n0, *p_n1, *p_n3),
			Ogre::Math::calculateBasicFaceNormal(*p_n1, *p_n2, *p_n3));
	}

	void Tile::set_terrain_type_for_vertex(unsigned short Vertex, unsigned short *pType)
	{
		assert(Vertex <= 4 && "Vertex out of index");
		m_TerrainTypeArray[Vertex] = pType;
	}

	unsigned short &Tile::get_terrain_type(unsigned short Vertex) const
	{
		assert(Vertex <= 4 && "Vertex out of index");
		return *m_TerrainTypeArray[Vertex];
	}
}